package com.gateway.filter;

import com.gateway.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * <dl>
 * <dd>描述: ~ 校验token</dd>
 * <dd>创建时间：  11:26 2020/5/13</dd>
 * <dd>创建人： zz</dd>
 * <dt>版本历史: </dt>
 * <pre>
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2020/5/13      guodong       1.0        1.0 Version
 * </pre>
 * </dl>
 */
@Component
public class AuthFilter implements GlobalFilter,Ordered{
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.判断请求地址---》如果是登录则放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if(path.contains("admin/login")){ //是登录请求
            return chain.filter(exchange);
        }
        //2.其他请求从request header中获取token
        //首先判断list是否为空，避免获取get(0) 空指针异常
        List<String> list = request.getHeaders().get("token");
        if(CollectionUtils.isEmpty(list)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String token = list.get(0);
        //3.对token判空
        if(StringUtils.isEmpty(token)){ //token为空
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4.进行解析---》异常(直接返回401)  正常(路由到真正的微服务)
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //校验失败
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    //优先级别必须小于2
    @Override
    public int getOrder() {
        return 1;
    }
}
